<html>

<head><title>SQL query</title></head>

<body>

<h3>Please type in your SQL query in the following box, then click Submit:</h3>

<p>

<form method="GET">

<textarea name="query" cols="60" rows="10">
<?php
echo $_GET['query'];
?>
</textarea>

<input type="submit" value="Submit" />

</form>

</p>

<h3>Result of the query: </h3>

<?php

/* establish connection to MySQL database system on the machine "localhost" */
/* using the username "cs143" and an empty password */
$db_connection = mysql_connect("localhost", "cs143", "");

/* specify the database "CS143" */
mysql_select_db("CS143", $db_connection);

/* issue the query obtained from the user input */
$rs = mysql_query( $_GET["query"], $db_connection );

if ($rs)
{
   /* get the number of columns */
   $col = mysql_num_fields ($rs);

   echo "<table border='1' style='text-align:center;'> <tr>";

   /* print out the column names */
   for( $i = 0; $i < $col; $i++ )
      echo "<th>". mysql_field_name($rs, $i) ."</th>";

   echo "</tr>";

   /* print out the results of query row by row */
   while( $row = mysql_fetch_row($rs) )
   {
      echo "<tr>";

      for( $i = 0; $i < $col; $i++ )
      {
         if (is_null($row[$i]))
            $row_i = "N/A";
         else
            $row_i = $row[$i];
         echo "<td>". $row_i ."</td>";
      }

      echo "</tr>";
   }

   echo "</table>";

}

/* close the connection */
mysql_close($db_connection);

?>

</body>

</html>
